//
//  LLNWReachabilityAFNetworking.m
//  LLFoundation
//
//  Created by my_liu on 2016/11/14.
//  Copyright © 2016年 . All rights reserved.
//

#import "LLNWReachabilityAFNetworking.h"
#import "AFNetworkReachabilityManager.h"

@interface LLNWReachabilityAFNetworking ()
{
    AFNetworkReachabilityManager *_reachability;
}
@end

@implementation LLNWReachabilityAFNetworking

- (id)initWithDefault
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
        _reachability = [AFNetworkReachabilityManager sharedManager];
    }
    return self;
}

- (id)initWithDomain:(NSString *)domain
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
        _reachability = [AFNetworkReachabilityManager managerForDomain:domain];
    }
    return self;
}

- (id)initWithAddress:(void *)address
{
    self = [super init];
    if ( self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
        _reachability = [AFNetworkReachabilityManager managerForAddress:address];
    }
    return self;
}

- (void)reachabilityChanged:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] postNotificationName:LLNWReachabilityDidChangeNotification object:self];
}

- (void)startMonitoring
{
    [_reachability startMonitoring];
}

- (void)stopMonitoring
{
    [_reachability stopMonitoring];
}

- (LLNWReachabilityStatus)networkReachabilityStatus
{
    LLNWReachabilityStatus state = LLNWReachabilityStatusUnknown;
    AFNetworkReachabilityStatus status = [_reachability networkReachabilityStatus];
    switch (status) {
        case AFNetworkReachabilityStatusNotReachable:
        {
            state = LLNWReachabilityStatusNotReachable;
            break;
            
        }
        case AFNetworkReachabilityStatusReachableViaWiFi:
        {
            state = LLNWReachabilityStatusReachableViaWiFi;
            break;
        }
        case AFNetworkReachabilityStatusReachableViaWWAN:
        {
            state = LLNWReachabilityStatusReachableViaWWAN;
            break;
        }
        default:
            break;
    }
    return state;
}

- (BOOL)isReachable
{
    return [_reachability isReachable];
}

- (BOOL)isReachableViaWWAN
{
    return [_reachability isReachableViaWWAN];
}

- (BOOL)isReachableViaWiFi
{
    return [_reachability isReachableViaWiFi];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNetworkingReachabilityDidChangeNotification object:nil];
}
@end
